import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    cartItems: [],
    tableNumber: 1,
    userInfo: null
  },
  
  mutations: {
    ADD_TO_CART(state, item) {
      const existingItem = state.cartItems.find(cartItem => cartItem.id === item.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        state.cartItems.push({ ...item, quantity: 1 })
      }
    },
    
    REMOVE_FROM_CART(state, itemId) {
      state.cartItems = state.cartItems.filter(item => item.id !== itemId)
    },
    
    UPDATE_QUANTITY(state, { itemId, quantity }) {
      const item = state.cartItems.find(item => item.id === itemId)
      if (item) {
        item.quantity = quantity
        if (item.quantity <= 0) {
          state.cartItems = state.cartItems.filter(i => i.id !== itemId)
        }
      }
    },
    
    CLEAR_CART(state) {
      state.cartItems = []
    },
    
    SET_TABLE_NUMBER(state, tableNumber) {
      state.tableNumber = tableNumber
    },
    
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  
  actions: {
    addToCart({ commit }, item) {
      commit('ADD_TO_CART', item)
    },
    
    removeFromCart({ commit }, itemId) {
      commit('REMOVE_FROM_CART', itemId)
    },
    
    updateQuantity({ commit }, payload) {
      commit('UPDATE_QUANTITY', payload)
    },
    
    clearCart({ commit }) {
      commit('CLEAR_CART')
    },
    
    setTableNumber({ commit }, tableNumber) {
      commit('SET_TABLE_NUMBER', tableNumber)
    },
    
    setUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    }
  },
  
  getters: {
    cartTotal: state => {
      return state.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
    },
    
    cartCount: state => {
      return state.cartItems.reduce((count, item) => count + item.quantity, 0)
    },
    
    cartItems: state => state.cartItems,
    tableNumber: state => state.tableNumber,
    userInfo: state => state.userInfo
  }
})

export default store